package com.mc.read.pcApi.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mc.read.common.constant.ApplicationValues;
import com.mc.read.common.constant.Constants;
import com.mc.read.common.emun.ServiceCodeEnum;
import com.mc.read.common.exception.ServiceException;
import com.mc.read.common.util.HttpRequestor;
import com.mc.read.common.util.SmsUtil;
import com.mc.read.dao.mapper.PhonecodeMapper;
import com.mc.read.dao.mapper.UserinformationMapper;
import com.mc.read.dao.mapper.UserinformationdetMapper;
import com.mc.read.dao.mapper.UseropinionMapper;
import com.mc.read.dao.models.*;
import com.mc.read.vo.request.BaseRequest;
import com.mc.read.vo.respose.BaseRespose;
import com.mc.read.dao.vo.LoginRequest;
import com.mc.read.dao.vo.PageResposeVo;
import com.mc.read.dao.vo.PageVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
public class UserService {
    @Autowired
    UserinformationdetMapper userinformationdetMapper;
    @Autowired
    UserinformationMapper userinformationMapper;
    @Autowired
    PhonecodeMapper phonecodeMapper;
    @Autowired
    UseropinionMapper useropinionMapper;
    @Autowired
    FunctionService functionService;

    /**
     * @Author:LiuHao
     * @Date:18:24 2019/5/30
     * 用户个人信息展示 selectUserInfo
     **/
    public BaseRespose selectUserInfo(BaseRequest baseRequest) {
        log.info("用户个人信息展示,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        UserinformationdetExample example = new UserinformationdetExample();
        example.createCriteria().andUseridEqualTo(baseRequest.getUserId());
        List<Userinformationdet> userinformationdetList = userinformationdetMapper.selectByExample(example);
        if (userinformationdetList.size() > 0) {
            baseRespose.setReturnString(userinformationdetList.get(0));
        } else {
            throw new ServiceException(203020, "未找到个人信息", JSON.toJSONString(baseRequest));
        }
        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:15:01 2019/5/31
     * 修改用户个人信息 updateUserInfodet
     **/
    public BaseRespose updateUserInfodet(BaseRequest baseRequest) {
        log.info("修改用户个人信息,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        Userinformationdet userinformationdet = null;
        try {
            userinformationdet = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), Userinformationdet.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        userinformationdet.setUserid(baseRequest.getUserId());
        userinformationdetMapper.updateByUserId(userinformationdet);
        baseRespose.setReturnString(" ");
        functionService.updateFunctionClick("修改个人信息");

        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:14:57 2019/5/31
     * 查询用户账号信息 selectUserAccount
     **/
    public BaseRespose selectUserAccount(BaseRequest baseRequest) {
        log.info("查询用户账号信息,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        baseRespose.setReturnString(userinformationMapper.selectByPrimaryKey(baseRequest.getUserId()));
        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:15:00 2019/5/31
     * 修改用户微信号 updateUserWx
     **/
    public BaseRespose updateUserWx(BaseRequest baseRequest) {
        log.info("修改用户微信号,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        LoginRequest loginRequest = null;
        try {
            loginRequest = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), LoginRequest.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        if (ObjectUtils.isEmpty(loginRequest.getCode())) {
            throw new ServiceException(203020, "微信code不能为空", JSON.toJSONString(baseRequest));
        }
        String code = loginRequest.getCode();
        String appid = ApplicationValues.getAppid();
        String secret = ApplicationValues.getAPPSECRET();
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
        //第一次请求 获取access_token 和 openid
        String oppid = null;
        JSONObject oppidObj = null;
        try {
            oppid = new HttpRequestor().doGet(requestUrl);
            log.info("微信登录返回：{}", oppid);
            oppidObj = JSON.parseObject(oppid);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(203020, "获取微信信息错误");
        }
        if (!ObjectUtils.isEmpty(oppidObj.get("errcode"))) {
            throw new ServiceException(203020, "获取微信信息错误");
        }
        String openid = (String) oppidObj.get("openid");
        if (ObjectUtils.isEmpty(oppid)) {
            throw new ServiceException(203020, "获取微信信息错误");
        }
        Userinformation userinformation = new Userinformation();
        userinformation.setUserid(baseRequest.getUserId());
        userinformation.setOpenid(openid);
        userinformationMapper.updateByPrimaryKeySelective(userinformation);
        baseRespose.setReturnString(" ");
        functionService.updateFunctionClick("修改微信号");

        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 用户更换手机号 发送验证码 sendSmsForUpdate
     **/
    public BaseRespose sendSmsForUpdate(BaseRequest baseRequest) {
        log.info("用户更换手机号 发送验证码,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        Userinformation userinformation = null;
        try {
            userinformation = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), Userinformation.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        if (ObjectUtils.isEmpty(userinformation.getPhone())) {
            throw new ServiceException(203020, "手机号不能为空", JSON.toJSONString(baseRequest));
        }
        String code = SmsUtil.getCode();
        SmsUtil.sendSms(userinformation.getPhone(), code);
        Phonecode phonecode = new Phonecode();
        phonecode.setCode(code);
        phonecode.setPhone(userinformation.getPhone());
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.MINUTE, Constants.PHONE_CODE_TIME);
        phonecode.setExpirationtime(c.getTime());
        phonecode.setUsed(0);
        phonecode.setUsetype(2);
        phonecodeMapper.insertSelective(phonecode);
        baseRespose.setReturnString(" ");
        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 用户更换手机 验证旧手机验证码 valOldPhone
     **/
    public BaseRespose valOldPhone(BaseRequest baseRequest) {
        log.info("用户更换手机 验证旧手机验证码,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        Phonecode phonecodeRequest = null;
        try {
            phonecodeRequest = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), Phonecode.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        Phonecode phonecode = phonecodeMapper.selectLastUpdate(phonecodeRequest.getPhone());
        if (ObjectUtils.isEmpty(phonecode) || !phonecode.getCode().equals(phonecodeRequest.getCode())) {
            throw new ServiceException(203020, "验证码错误，请输入正确的验证码", JSON.toJSONString(baseRequest));
        }

        if (phonecode.getUsed() != 0) {
            throw new ServiceException(203020, "该验证码已使用过或已失效，请重新发送新的验证码");
        }
        if (new Date().getTime() > phonecode.getExpirationtime().getTime()) {
            throw new ServiceException(203020, "验证码以过期，请重新发送");
        }
        phonecode.setUsed(1);
        phonecodeMapper.updateByPrimaryKeySelective(phonecode);
        baseRespose.setReturnString(" ");
        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 用户更换手机 确认更换 updateUserPhone
     **/
    public BaseRespose updateUserPhone(BaseRequest baseRequest) {
        log.info("用户更换手机 确认更换,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        Phonecode phonecodeRequest = null;
        try {
            phonecodeRequest = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), Phonecode.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        Phonecode phonecode = phonecodeMapper.selectLastUpdate(phonecodeRequest.getPhone());
        if (ObjectUtils.isEmpty(phonecode) || !phonecode.getCode().equals(phonecodeRequest.getCode())) {
            throw new ServiceException(203020, "验证码错误，请输入正确的验证码", JSON.toJSONString(baseRequest));
        }

        if (phonecode.getUsed() != 0) {
            throw new ServiceException(203020, "该验证码已使用过或已失效，请重新发送新的验证码");
        }
        if (new Date().getTime() > phonecode.getExpirationtime().getTime()) {
            throw new ServiceException(203020, "验证码以过期，请重新发送");
        }
        phonecode.setUsed(1);
        phonecodeMapper.updateByPrimaryKeySelective(phonecode);

        UserinformationExample example = new UserinformationExample();
        example.createCriteria().andPhoneEqualTo(phonecodeRequest.getPhone());
        List<Userinformation> userinformationList = userinformationMapper.selectByExample(example);
        if (userinformationList.size() > 0) {
            throw new ServiceException(203020, "该手机已被注册了", JSON.toJSONString(baseRequest));
        }
        Userinformation userinformation = new Userinformation();
        userinformation.setUserid(baseRequest.getUserId());
        userinformation.setPhone(phonecodeRequest.getPhone());
        userinformationMapper.updateByPrimaryKeySelective(userinformation);
        baseRespose.setReturnString(" ");
        functionService.updateFunctionClick("更换手机号");

        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 用户查询意见反馈列表 selectUserOpinionList
     **/
    public BaseRespose selectUserOpinionList(BaseRequest baseRequest) {
        log.info("用户查询意见反馈列表,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        PageVo pageVo = null;
        try {
            pageVo = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), PageVo.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        PageHelper.startPage(pageVo.getPagenum(), pageVo.getPagesize());
        PageHelper.orderBy("createDate desc");
//        UseropinionExample example = new UseropinionExample();
//        example.createCriteria().andUseridEqualTo(baseRequest.getUserId());
        pageVo.setUserid(baseRequest.getUserId());
        List<Useropinion> useropinionList = useropinionMapper.selectUserOpinionList(pageVo);
        PageInfo<Useropinion> pageInfo = new PageInfo<>(useropinionList);
        PageResposeVo pageResposeVo = new PageResposeVo(pageInfo.getTotal(), pageInfo.getList());
        baseRespose.setReturnString(pageResposeVo);
        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 用户 提交意见反馈 addUserOpinion
     **/
    public BaseRespose addUserOpinion(BaseRequest baseRequest) {
        log.info("用户 提交意见反馈,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        Useropinion useropinion = null;
        try {
            useropinion = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), Useropinion.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        if (ObjectUtils.isEmpty(useropinion.getOpiniondescribe())&&ObjectUtils.isEmpty(useropinion.getPicurl())) {
            throw new ServiceException(203020, "意见描述和意见图片不能同时为空", JSON.toJSONString(baseRequest));
        }
        useropinion.setUserid(baseRequest.getUserId());
        useropinion.setCreatedate(new Date());
        useropinionMapper.insertSelective(useropinion);
        baseRespose.setReturnString(" ");
        functionService.updateFunctionClick("提交意见反馈");

        return baseRespose;
    }

    /**
     * @Author:LiuHao
     * @Date:15:24 2019/5/31
     * 用户 标记已处理的意见反馈 updateOpinionState
     **/
    public BaseRespose updateOpinionState(BaseRequest baseRequest) {
        log.info("用户 标记已处理的意见反馈,参数为{}", JSON.toJSONString(baseRequest));
        BaseRespose baseRespose = new BaseRespose();
        Useropinion useropinion = null;
        try {
            useropinion = JSON.parseObject(JSON.toJSONString(baseRequest.getRequestString()), Useropinion.class);
        } catch (Exception e) {
            throw new ServiceException(ServiceCodeEnum.INFO_IS_FAIL, JSON.toJSONString(baseRequest));
        }
        if (ObjectUtils.isEmpty(useropinion.getUseropinionid())) {
            throw new ServiceException(203020, "请选择要标记的记录", JSON.toJSONString(baseRequest));
        }
        Useropinion useropinion1 = useropinionMapper.selectByPrimaryKey(useropinion.getUseropinionid());
        if (ObjectUtils.isEmpty(useropinion1)) {
            throw new ServiceException(203020, "未找到该记录", JSON.toJSONString(baseRequest));
        }
        if (useropinion1.getIsdeal() != 2) {
            throw new ServiceException(203020, "只能标记已处理的记录", JSON.toJSONString(baseRequest));
        }
        if (useropinion1.getIssettle() != 1) {
            throw new ServiceException(203020, "只能标记未标记的记录", JSON.toJSONString(baseRequest));
        }
        useropinion1.setIssettle(useropinion.getIssettle());
        useropinionMapper.updateByPrimaryKeySelective(useropinion1);
        baseRespose.setReturnString(" ");
        functionService.updateFunctionClick("标记意见反馈");

        return baseRespose;
    }


}
